package com.example.dp.jiemian.bt3;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dp.jiemian.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;

public class bt3 extends AppCompatActivity {

    private Button bt3_bt1,bt3_bt2;
    private ImageView bt3_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bt3);
        bt3_bt1 = findViewById(R.id.bt3_bt1);
        bt3_iv = findViewById(R.id.bt3_iv);
        bt3_bt2 = findViewById(R.id.bt3_bt2);
        onTakePhotoClicked(bt3_bt1);
        bt3_bt2.setOnClickListener(v -> {
            OkHttpUtils.get().url("http://47.106.84.140:8080/api/img/getimg").build().execute(new MyStringCallback());
        });
    }

    public void onTakePhotoClicked(View view) {
        final SurfaceView preview = new SurfaceView(this);
        SurfaceHolder holder = preview.getHolder();
        // deprecated setting, but required on Android versions prior to 3.0
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            //The preview must happen at or after this point or takePicture fails
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d("Tag", "Surface created");
                Camera camera = null;
                try {
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                    Log.d("Tag", "Opened camera");

                    try {
                        camera.setPreviewDisplay(holder);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    camera.startPreview();
                    Log.d("Tag", "Started preview");
                    camera.takePicture(null, null, pictureCallback);
                } catch (Exception e) {
                    if (camera != null)
                        camera.release();
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }
        });

        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                1, 1, //Must be at least 1x1
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                0,
                //Don't know if this is a safe default
                PixelFormat.UNKNOWN);

        //Don't set the preview visibility to GONE or INVISIBLE
        wm.addView(preview, params);
    }

    private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Log.d("Tag", "onPictureTaken");
            if (null == data) {
                return;
            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            camera.stopPreview();
            Matrix matrix = new Matrix();
            matrix.postRotate((float) 90.0);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, false);
            Log.d("Tag", "original bitmap width: " + bitmap.getWidth() +
                    " height: " + bitmap.getHeight());
            Bitmap sizeBitmap = Bitmap.createScaledBitmap(bitmap,
                    bitmap.getWidth() / 3, bitmap.getHeight() / 3, true);
            Log.d("Tag", "size bitmap width " + sizeBitmap.getWidth() + " height " + sizeBitmap.getHeight());
            bt3_iv.setImageBitmap(bitmap);//bitmap
            initView(bitmap);
            OkHttpUtils.post().url("http://47.106.84.140:8080/api/img/fA").addFile("file","01.jpg",file).
                    addParams("lal","2").addParams("time","3").
                    build().execute(new MyStringCallback());
        }
    };

    File file;
    @SuppressLint("SdCardPath")
    private void initView(Bitmap bitmap) {
        file = new File("/mnt/sdcard/01.jpg");
        //判断文件是否存在，存在就删除
        if (file.exists()){
            file.delete();
        }
        try {
            //创建文件
            file.createNewFile();
            //给一个吐司提示，显示创建成功
            Toast.makeText(getApplicationContext(), "文件创建成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String str1 = bitmapToBase64(bitmap);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //图片转换成base64
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private class MyStringCallback extends StringCallback {

        @Override
        public void onError(Call call, Exception e, int id) {
            Log.d("1231231", String.valueOf(e));
        }

        @Override
        public void onResponse(String response, int id) {
            Log.d("123123", String.valueOf(response));
        }
    }
}
